package com.example.servletdemo.servlet.ajax;

import com.alibaba.fastjson.JSON;
import com.example.servletdemo.model.Result;
import com.example.servletdemo.model.User;
import com.sun.xml.internal.ws.util.StreamUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        //解析参数
        InputStreamReader insr = new InputStreamReader(req.getInputStream(),"utf-8");
        String res = "";
        int respInt = insr.read();
        while(respInt!=-1) {
            res +=(char)respInt;
            respInt = insr.read();
        }
        User user=JSON.parseObject(res,User.class);
        //返回结果
        Result result = new Result();
        if(user.getUsername()==null||user.getUsername().isEmpty()){
            result.setSuccess(false);
            result.setErrorCode(-1);
            result.setErrorMsg("请输入用户名");
        }else if(user.getPassword()==null||user.getPassword().isEmpty()){
            result.setSuccess(false);
            result.setErrorCode(-1);
            result.setErrorMsg("请输入密码");
        }else if(!user.getUsername().equals("admin")||!user.getPassword().equals("admin")){
            result.setSuccess(false);
            result.setErrorCode(-1);
            result.setErrorMsg("用户名或者密码错误");
        }else {
            result.setSuccess(true);
        }
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(result));
    }
}
//{"errorCode":-1,"errorMsg":"请输入用户名","success":false}
